/**

This file is part of MaCI/GIMnet.

MaCI/GIMnet is free software: you can redistribute it and/or modify it 
under the terms of the GNU Lesser General Public License as published 
by the Free Software Foundation, either version 3 of the License, or 
(at your option) any later version.

MaCI/GIMnet is distributed in the hope that it will be useful, but WITHOUT 
ANY WARRANTY; without even the implied warranty of MERCHANTABILITY or 
FITNESS FOR A PARTICULAR PURPOSE.  See the GNU Lesser General Public 
License for more details.

You should have received a copy of the GNU Lesser General Public 
License along with GIMnet. (See COPYING.LESSER) If not, see 
<http://www.gnu.org/licenses/>.

**/
/**
 *
 * $Id: EnvironmentMeasurementClient.cpp,v 1.5 2009-10-23 13:56:43 morsko Exp $
 *
 * \file
 * \brief Implementation for EnvironmentMeasurement interface client library.
 * \author Matthieu Myrsky <matthieu.myrsky@tkk.fi>
 */

#include "EnvironmentMeasurementClient.hpp"
#include "EnvironmentMeasurementData.hpp"

//*****************************************************************************
using namespace MaCI::EnvironmentMeasurement;
//*****************************************************************************
//*****************************************************************************
#define GIMI_CLIENT_API (20000)
#include "gimi.h"
//*****************************************************************************
//*****************************************************************************
//*****************************************************************************

CEnvironmentMeasurementClient::CEnvironmentMeasurementClient(gimi::GIMI *aGIMIPtr, 
                           const int aInterfaceMinor)
  : CSync(1,1), // Max One Mutex, Max one Condition
    CThread(1), // Max one Thread.
    CMaCI(aGIMIPtr, GIMI_PROTOCOL_MACI_ENVIRONMENTMEASUREMENT, aInterfaceMinor),
    iEnvironmentMeasurementCommandSequence(0)  
{
  dPrint(4,"CEnvironmentMeasurementClient %p constructed", this);
}
//*****************************************************************************

CEnvironmentMeasurementClient::~CEnvironmentMeasurementClient()
{
  DoClose();
  dPrint(4,"CEnvironmentMeasurementClient %p destructed", this);
}
//*****************************************************************************

MaCI::EMaCIError CEnvironmentMeasurementClient::DoOpen(void)
{

  EMaCIError result = KMaCIError;
  
  // Checks.
  if(!IsActive()) {

    // Do Subs. using the MaCI provided function.
    result = SubscribeToInterface();

    // If all inits were fine...
    if (result == KMaCIOK) {
      // Start the Thread
      SetActive(true);
      result = EnableSynchronousMessageReply();
      CThread::RunThread();
      dPrint(4,"CEnvironmentMeasurementClient::DoOpen() was succesfull.");
    }

  } else {
    dPrint(4,"EnvironmentMeasurementClient already Active, not Opening again.");
    result = KMaCINotActive;

  }
  
  return result;
}
//*****************************************************************************

MaCI::EMaCIError CEnvironmentMeasurementClient::DoClose(void)
{
  EMaCIError result = KMaCIError;
  
  if(IsActive()) {
    SetActive(false);

    // Wait for thread to complete.
    /* CThread::CancelThread(); //Removed by script */
    CThread::WaitThread();
    result = UnsubscribeToInterface(TimeoutValue(2000));
  
    if(result == KMaCIOK){
      dPrint(4,"Succesfully closed EnvironmentMeasurementClient");    
    }else{
      dPrint(4,"Unsubscribing failed at EnvironmentMeasurementClient!");
    }

    
  } else {
    dPrint(4, "EnvironmentMeasurementClient not active, so not Closing.");
    result = KMaCINotActive;

  }
  
  return result;
}
//*****************************************************************************

bool CEnvironmentMeasurementClient::GetPositionWithEnvironment(CEnvironmentMeasurement2D &aEnvData, 
                                                               CEnvironmentMeasurementData *aReplyData, 
                                                               const int aTimeout_ms)
{
 
  CEnvironmentMeasurementData environmentData;
  environmentData.CreateInternalBinBag();

  // Only this func uses the sequence, so locking not required; BUT remember
  // correct locking scheme when this is not the case.
  ++iEnvironmentMeasurementCommandSequence;
      
   
  // Add a dummy event
  if(!environmentData.SetCommand(TCommand(KCommandGetPositionWithEnvironment))){
    dPrint(1,"Failed to set command");
    return false;
  }
  if(!environmentData.SetEnvironmentMeasurement(&aEnvData)){
    dPrint(1,"Failed to set environment measurement");
    return false;
  }
  
  // Send! ( Should probably check the Send() - but timeouted receive
  // gives the same )
  SendCommand(environmentData, iEnvironmentMeasurementCommandSequence);

  // Now, get reply! (Give it 1000ms time to answer)
  return GetCommandReply(*aReplyData, iEnvironmentMeasurementCommandSequence, aTimeout_ms);


}
//*****************************************************************************

bool CEnvironmentMeasurementClient::GetCommandReply(CEnvironmentMeasurementData &aData, 
                                   const int aMessageID, 
                                   const int aTimeout_ms)
{ 
  EMaCIError result;
  gimi::GIMIMessage gmsg;
  
  // Call the ReceiveMessage wrapper with 2s timeout
  result = ReceiveSynchronousMessageReply(gmsg, aMessageID, aTimeout_ms);
  
  // If result is OK, process the msg.
  if (result == KMaCIOK) {
    bool r;
    gim::binbag::CBinBag bb;
    CEnvironmentMeasurementData d;

    // Decode BinBag.
    r = bb.Decode(gmsg.getData(), gmsg.getDatalength());
    if (r) {
      // BinBag OK. Decode DummyData.
      r = d.DecodeFrom(&bb);
      if (r) {
        // DummyData ok. Copy to caller.
        aData.Copy(d);

      } else {
        result = KMaCIInvalidFormat;

      }

    } else {
      result = KMaCIInvalidFormat;
      
    }
  }
  
  return (result == KMaCIOK);
}
//*****************************************************************************

bool CEnvironmentMeasurementClient::SendCommand(const CEnvironmentMeasurementData &aEnvData, const int aMessageID)
{
  EMaCIError result = KMaCIError;
  
  if (IsActive()) {
    if (aEnvData.GetCommand()) {
      // Send.
      SendInterfaceMessage(aEnvData.GetBinBagContainerPtr()->GetBuffer(),
                           aEnvData.GetBinBagContainerPtr()->GetBufferSize(),
                           aMessageID);
      
      dPrint(10,"SendInterfaceMessage called: %d:%d (%d bytes of payload sent)",
             iInterfaceMajor, iInterfaceMinor, 
             aEnvData.GetBinBagContainerPtr()->GetBufferSize());

      // Result
      result = KMaCIOK;
      
    } else {
      dPrint(2,"No 'TCommand' element in provided CEnvironmentMeasurementData object. Will not send!");
      result = KMaCIInvalidFormat;

    }
   
  } else {
    dPrint(2,"Unable to send EnvironmentData - Interface is not active! (Open() not called?)");
    result = KMaCINotActive;

  }


  return (result == KMaCIOK);
}
//*****************************************************************************
//*****************************************************************************
//*****************************************************************************
//*****************************************************************************
//*****************************************************************************
//*****************************************************************************
//*****************************************************************************
//*****************************************************************************
//*****************************************************************************
//*****************************************************************************

int CEnvironmentMeasurementClient::ProcessMessage(const gimi::GIMIMessage &msg)
{
  int result = 0;
  gim::binbag::CBinBag bb;
  CEnvironmentMeasurementData id;
  bool r;

  r = bb.Decode(msg.getData(), msg.getDatalength());
  if (r) {
    // Succesfully decoded as BinBag.
    r = id.DecodeFrom(&bb);
    if (r) {
      // Succesfully decoded as EnvironmentMeasurement, now handle contents
      Lock();
     
      Unlock();
      
     

    } else {
      dPrint(4,"WARNING: Received EnvironmentMeasurement interface message, but failed to decode as EnvironmentMeasurementData!");
      
    }
  }
  
  return result;
}

//*****************************************************************************

int CEnvironmentMeasurementClient::ThreadFunction(const int aThreadNumber)
{
  int result = 0;
  const unsigned int hard_error_count_limit = 10;
  unsigned int hard_error_count = 0;
  EMaCIError e;
  gimi::GIMIMessage gmsg;
  
  assert(aThreadNumber == 0);
  assert(iGIMIPtr != NULL);
  
  dPrint(8, "GIMIMessage handler started");
  
  // Run as long as the thread should be active
  while(IsActive()) {
    // Call the ReceiveMessage wrapper with 1s timeout
    e = ReceiveInterfaceMessage(gmsg, 1000);
    if (e == KMaCIOK) {
      ProcessMessage(gmsg);

      // Reset error counter.
      if (hard_error_count) hard_error_count = 0;

    } else if (e != KMaCITimeout) {
      // Increment hard error count
      ++hard_error_count;
      
      // Check whether the hard error count limit is still under limit. 
      if (hard_error_count < hard_error_count_limit) {
        // Other error, try to recover by sleeping one second.
        dPrint(10,"ProcessMessage returned error %u, trying to recover by sleeping 1000ms (%u attempts left)",
               e, hard_error_count_limit-hard_error_count);
        ownSleep_ms(1000);

      } else {
        dPrint(3,"Error Recovery failed, EnvironmentMeasurementClient ThreadFunction terminating...");

        // Break the while().
        break;
      }
      
    }
  }
  
  dPrint(8, "GIMIMessage handler stopped");
  SetActive(false);

  return result;
}
//*****************************************************************************
//*****************************************************************************
//*****************************************************************************
//*****************************************************************************
